package org.chupito.ui.controller;

import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.chupito.data.Invoice;
import org.chupito.search.InvoiceSearch;
import org.chupito.service.InvoiceService;
import org.jboss.logging.Logger;
import org.primefaces.event.SelectEvent;

@ManagedBean(name = "invoiceController")
@SessionScoped
public class InvoiceController implements Serializable {

	private Invoice selected;
	private InvoiceSearch search;

	private List<Invoice> invoices;

	private static final String INVOICE_LIST_PAGE = "/pages/content/invoice/invoiceOpened.xhtml";
	private static final String INVOICE_EDIT_PAGE = "/pages/content/invoice/editInvoice.xhtml";

	@EJB(name = "InvoiceService")
	private InvoiceService invoiceService;

	/**
	 * 
	 */
	private static final long serialVersionUID = 1928199179531048056L;

	public InvoiceController() {
	}

	@PostConstruct
	private void init() {
		this.selected = new Invoice();
		this.search = new InvoiceSearch();
		this.invoices = invoiceService.find(new InvoiceSearch());
	}

	public void save() {
		invoiceService.save(selected);
	}

	public String saveAndClose() {
		invoiceService.save(selected);
		return INVOICE_LIST_PAGE;
	}

	public String onRowSelect(SelectEvent event) {
		selected = ((Invoice) event.getObject());
		return INVOICE_LIST_PAGE;
	}

	public String newInvoice() {
		selected = new Invoice();
		return INVOICE_EDIT_PAGE;
	}
	
	public void find() {
		Logger.getLogger(InvoiceController.class).info(" find ");
		this.invoices = this.invoiceService.find(search);
	}
	
	public void clear() {
		search = null;
		search = new InvoiceSearch();
		find();
	}
	
	//-------------------------- Getter & Setters ----------------------------
	
	public InvoiceSearch getSearch() {
		return search;
	}
	
	public void setSearch(InvoiceSearch search) {
		this.search = search;
	}
	
	public void setSelected(Invoice selected) {
		Logger.getLogger(getClass()).info("Set selected " + selected.toString());
		this.selected = selected;
	}

	public Invoice getSelected() {
		return selected;
	}

	public List<Invoice> getInvoices() {
		return invoices;
	}

	public void setInvoices(List<Invoice> invoices) {
		this.invoices = invoices;
	}
}
